<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小账单物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\controller\property\bill;

use think\App;
use app\controller\property\Base;
use app\validate\bill\BillBasicValidate;
use app\common\repositories\bill\BillLogRepository;
use app\common\repositories\bill\BillCateRepository;
use app\common\repositories\bill\BillBasicRepository;
use app\common\repositories\room\RoomBasicRepository;
use app\common\repositories\property\basic\PropertyBasicRepository;

class BillBasic extends Base
{

    protected $repository;

    public function __construct(App $app, BillBasicRepository $repository)
    {
        parent::__construct($app);

        $this->repository = $repository;
        $this->assign([
            'addAuth' => property_auth('propertyBillBasicAdd'),
            'editAuth' => property_auth('propertyBillBasicEdit'),
            'delAuth' => property_auth('propertyBillBasicDel'),
            'detailAuth' => property_auth('propertyBillBasicDetail'),
            'invalidAuth' => property_auth('propertyBillInvalidSubmit'),
            'paymentAuth' => property_auth('propertyBillPaymentSubmit'),
            'postponeAuth' => property_auth('propertyBillPostponeSubmit'),
            'auditAuth' => property_auth('propertyBillAuditSubmit'),
            'paymentCustomAuth' => property_auth('propertyBillCatalogPaymentCustom'),
        ]);
    }

    protected function commonParams()
    {
        /** @var BillCateRepository $cateRepository */
        $cateRepository = app()->make(BillCateRepository::class);
        $cateNameData = $cateRepository->getCascaderData($this->request->propertyId, ['is_show' => 1]);
        $this->assign([
            'cateNameData' => $cateNameData,
        ]);
    }


    /**
     *  账单列表
     * @return string|\think\response\Json
     * @throws \Exception
     *
     * @author Amos
     * 2024-01-30 10:48
     */
    public function list()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'contract_id' => '',
                'room_id' => '',
                'keywords' => ''
            ]);
            $where['is_type'] = 1;
            [$page, $limit] = $this->getPage();
            $data = $this->repository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $data['list'], 'count' => $data['count']]);
        }
        return $this->fetch('bill/basic/list');
    }

    /**
     * 待审核账单
     * @return string|\think\response\Json
     * @throws \Exception
     *
     * @author Amos
     * 2024-03-15 10:31
     */
    public function stayAuditList()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'contract_id' => '',
                'room_id' => '',
                'month_time' => '',
                'keywords' => '',
            ]);
            $where['status'] = 1;
            $where['is_type'] = 1;
            [$page, $limit] = $this->getPage();
            $res = $this->repository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        }
        return $this->fetch('bill/basic/stay_audit_list');
    }

    /**
     * 待支付账单
     * @return string|\think\response\Json
     * @throws \Exception
     *
     * @author Amos
     * 2024-03-15 16:33
     */
    public function stayPaymentList()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'contract_id' => '',
                'room_id' => '',
                'month_time' => '',
                'keywords' => '',
            ]);
            $where['is_type'] = 1;
            $where['status'] = [2, 8];
            [$page, $limit] = $this->getPage();
            $res = $this->repository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        }
        ## 检测待支付订单状态
        $this->repository->checkStayPaymentListBill();
        return $this->fetch('bill/basic/stay_payment_list');
    }

    /**
     * 已逾期账单
     * @return string|\think\response\Json
     * @throws \Exception
     *
     * @author Amos
     * 2024-03-15 16:33
     */
    public function overdueList()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'contract_id' => '',
                'room_id' => '',
                'month_time' => '',
                'keywords' => '',
            ]);
            $where['status'] = 5;
            $where['is_type'] = 1;
            [$page, $limit] = $this->getPage();
            $res = $this->repository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        }
        return $this->fetch('bill/basic/overdue_list');
    }

    /**
     * 己作废
     * @return string|\think\response\Json
     * @throws \Exception
     *
     * @author Amos
     * 2024-03-15 16:33
     */
    public function hasInvalidList()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'contract_id' => '',
                'room_id' => '',
                'month_time' => '',
                'keywords' => '',
            ]);
            $where['status'] = 4;
            $where['is_type'] = 1;
            [$page, $limit] = $this->getPage();
            $res = $this->repository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        }
        return $this->fetch('bill/basic/has_invalid_list');
    }

    /**
     * 己完成
     * @return string|\think\response\Json
     * @throws \Exception
     *
     * @author Amos
     * 2024-03-15 16:33
     */
    public function hasSucceedList()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'room_id' => '',
                'contract_id' => '',
                'month_time' => '',
                'keywords' => '',
            ]);
            $where['status'] = 4;
            $where['is_type'] = 1;
            [$page, $limit] = $this->getPage();
            $res = $this->repository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        }
        return $this->fetch('bill/basic/has_succeed_list');
    }


    /**
     * 添加账单
     * @return string|\think\response\Json|\think\response\View
     * @throws \Exception
     *
     * @author Amos
     * 2024-01-30 10:48
     */
    public function add()
    {
        if ($this->request->isAjax() && $this->request->isGet() && $this->request->param('get_type') == 'roomData') {
            /** @var RoomBasicRepository; $roomRepository */
            $roomRepository = app()->make(RoomBasicRepository::class);
            $roomData = $roomRepository->getSearch([])
                ->where('status', 2)
                ->where('property_id', $this->request->propertyId)
                ->field('id,status,contract_id,unit_id,floor_name,room_name')
                ->append(['full_room_name'])
                ->select()->toArray();
            $roomData['number'] = $this->repository->generateBillNumber($this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $roomData]);
        } else if ($this->request->isPost()) {
            $param = $this->request->param([
                'number' => '',
                'cutoff_date' => '',
                'overdue_fine_fee' => '',
                'room_id' => '',
                'other_fee' => [],
                'remark' => '',
            ]);
            $param['is_type'] = 1;
            $param['bill_type'] = 4;
            $param['month_time'] = date('Y-m');
            validate(BillBasicValidate::class)->scene('add')->check($param);
            if ($this->repository->fieldExists('number', $param['number'])) {
                return $this->error('账单编号' . $param['number'] . '已存在');
            }
            /** @var RoomBasicRepository; $roomRepository */
            $roomRepository = app()->make(RoomBasicRepository::class);
            $roomInfo = $roomRepository->get($param['room_id']);
            $param['contract_id'] = $roomInfo['contract_id'];
            try {
                $res = $this->repository->addInfo($param, $this->request->propertyId, $this->request->userId);
                if ($res) {
                    return $this->success('添加成功');
                } else {
                    return $this->error('添加失败');
                }
            } catch (\Exception $e) {
                exception_log('添加账单失败', $e);
                return $this->error('网络失败');
            }
        } else {
            $this->commonParams();
            return $this->fetch('bill/basic/add');
        }
    }

    /**
     * 编辑账单
     * @return string|\think\response\Json|\think\response\View
     * @throws \Exception
     *
     * @author Amos
     * 2024-01-30 10:48
     */
    public function edit()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($id);
        if (!$info) {
            return $this->error('信息错误');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'remark' => '',
            ]);
            validate(BillBasicValidate::class)->scene('edit')->check($param);
            try {
                $res = $this->repository->editInfo($info, $param, $this->request->userId);
                if ($res) {
                    return $this->success('修改成功');
                } else {
                    return $this->error('修改失败');
                }
            } catch (\Exception $e) {
                exception_log('编辑账单失败', $e);
                return $this->error('网络错误');
            }
        } else {
            return $this->fetch('bill/basic/edit', [
                'info' => $info,
            ]);
        }
    }

    /**
     * 账单详情
     * @return string|\think\response\Json|\think\response\View
     * @throws \Exception
     *
     * @author Amos
     * 2024-01-30 19:09
     */
    public function detail()
    {
        $billId = (int)$this->request->param('bill_id');
        if ($billId <= 0) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($billId);
        if ($info['id'] <= 0) {
            return $this->error('信息不存在');
        }

        return $this->fetch('bill/basic/detail', [
            'info' => $info,
            'addBasicAuth' => property_auth('propertyBillCatalogAddBasic'),
            'addEnergyAuth' => property_auth('propertyBillCatalogAddEnergy'),
            'addOtherAuth' => property_auth('propertyBillCatalogAddOther'),
            'editCatalogAuth' => property_auth('propertyBillCatalogEdit'),
            'delCatalogAuth' => property_auth('propertyBillCatalogDel'),
            'detailCatalogAuth' => property_auth('propertyBillCatalogDetail'),
        ]);
    }

    /**
     * 删除账单
     * @return string|\think\response\Json|\think\response\View
     *
     * @author Amos
     * 2024-01-30 10:47
     */
    public function del()
    {
        $ids = (array)$this->request->param('ids');
        $remark = $this->request->param('remark', '');
        try {
            $data = $this->repository->batchDelete($ids, $this->request->userId, $remark);
            if ($data) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败');
            }
        } catch (\Exception $e) {
            exception_log('删除账单失败', $e);
            return $this->error('网络失败');
        }
    }

    public function auditAdd()
    {
        $ids = (array)$this->request->param('ids');
        try {
            $data = $this->repository->batchAuditBill($ids, $this->request->userId);
            if ($data) {
                return $this->success('审核成功');
            } else {
                return $this->error('审核失败');
            }
        } catch (\Exception $e) {
            exception_log('账单审核失败', $e);
            return $this->error('网络错误');
        }
    }

    /**
     * 作废账单
     *
     * @return string|\think\response\Json|\think\response\View
     *
     * @author Amos
     * 2024-03-15 10:58
     */
    public function invalidAdd()
    {
        $ids = (array)$this->request->param('ids');
        $remark = $this->request->param('remark', '');
        try {
            $data = $this->repository->batchInvalidBill($ids, $this->request->userId, $remark);
            if ($data) {
                return $this->success('作废成功');
            } else {
                return $this->error('作废失败');
            }
        } catch (\Exception $e) {
            exception_log('作废账单失败', $e);
            return $this->error('网络错误');
        }
    }

    /**
     * 延期账单
     * @return string|\think\response\Json|\think\response\View
     *
     * @author Amos
     * 2024-03-15 11:19
     */
    public function postponeAdd()
    {
        $ids = (array)$this->request->param('ids');
        $day = (int)$this->request->param('day');
        try {
            $data = $this->repository->batchPostponeBill($ids, $day, $this->request->userId);
            if ($data) {
                return $this->success('延期成功');
            } else {
                return $this->error('延期失败');
            }
        } catch (\Exception $e) {
            exception_log('延期账单失败', $e);
            return $this->error('网络错误');
        }
    }


    /**
     * 账单支付
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-03-15 21:02
     */
    public function paymentAdd()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'id' => '',
                'remark' => '',
                'picture' => '',
                'pay_amount' => '',
                'pay_method' => '',
                'amount_type' => '',
            ]);
            validate(BillBasicValidate::class)->scene('payment')->check($param);
            $ids = array_filter(explode(',', $param['id']));
            $num = 0;
            foreach ($ids as $v) {
                $info = $this->repository->get($v);
                if (isset($info) && $info['id'] > 0 && ($info['status'] == 2 || $info['status'] == 5 || $info['status'] == 8)) {
                    $res = $this->repository->paymentBill($info, $param, $this->request->userId);
                    if ($res) {
                        $num++;
                    }
                }
            }
            if ($num) {
                return $this->success('成功支付 ' . $num . ' 份账单');
            } else {
                return $this->error('账单支付失败');
            }
        } else {
            $id = $this->request->param('id');
            $ids = array_filter(explode(',', $id));
            $stayPaylist = $this->repository->getSearch([])
                ->where('id', 'in', $ids)
                ->where('status', 'in', '2,5,8')
                ->with([
                    'roomInfo' => function ($query) {
                        $query->bind(['full_room_name']);
                    },
                    'userInfo' => function ($query) {
                        $query->field('id,username');
                        $query->bind(['username' => 'username']);
                    },
                ])
                ->field('id,user_id,room_id,number,cutoff_date')
                ->append(['stay_payment_amount'])
                ->select()->toArray();
            $stayPayoney = array_sum(get_arr_column($stayPaylist, 'stay_payment_amount'));
            if ($stayPayoney <= 0) {
                return $this->error('该订单己支付完毕，禁止重复操作');
            }
            $this->assign([
                'repairData' => $stayPaylist,
                'stayPayoney' => $stayPayoney,
            ]);
            return $this->fetch('bill/basic/payment_add');
        }
    }


    public function billLog(BillLogRepository $logRepository)
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'bill_id' => '',
            ]);
            [$page, $limit] = $this->getPage();
            $res = $logRepository->getList($where, $page, $limit);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        }
    }

}